<template>
  <div class="tree-editor">
    <!-- 空状态 -->
    <div v-if="isEmptyData" class="empty-state">
      <el-button type="success" plain @click="addRootNode"
        >添加根节点</el-button
      >
    </div>

    <!-- 树形结构 -->
    <div v-else class="tree-container">
      <TreeNode
        v-for="(node, index) in treeData"
        :key="node.id"
        :isTree="isTree"
        :node="node"
        :level="0"
        @update-node="updateNode"
        @add-child="addChild"
        @add-sibling="addSibling"
        @remove-node="removeNode"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import TreeNode from './TreeNode.vue';

// 定义Props接口
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  isTree: {
    type: Boolean,
    default: true,
  },
});

// 定义Emits接口
const emit = defineEmits(['update:modelValue']);

// 内部数据
const treeData = ref([]);

// 计算属性判断是否为空
const isEmptyData = computed(() => treeData.value.length === 0);

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 初始化数据
const initializeData = () => {
  if (Array.isArray(props.modelValue) && props.modelValue.length > 0) {
    treeData.value = props.modelValue.map((item) => ({
      ...item,
      id: item.id || generateId(),
      children: item.children || [],
    }));
  } else {
    treeData.value = [];
  }
};

// 创建新节点
const createNewNode = () => ({
  id: generateId(),
  label: '',
  value: '',
  tagType: 'primary',
  children: [],
});

// 添加根节点
const addRootNode = () => {
  treeData.value.push(createNewNode());
  updateModelValue();
};

// 查找节点
const findNode = (nodes, nodeId) => {
  for (let node of nodes) {
    if (node.id === nodeId) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const found = findNode(node.children, nodeId);
      if (found) return found;
    }
  }
  return null;
};

// 查找父节点
const findParentNode = (nodes, targetId, parent = null) => {
  for (let node of nodes) {
    if (node.id === targetId) {
      return parent;
    }
    if (node.children && node.children.length > 0) {
      const found = findParentNode(node.children, targetId, node);
      if (found !== null) return found;
    }
  }
  return null;
};

// 更新节点
const updateNode = (nodeId, updates) => {
  const node = findNode(treeData.value, nodeId);
  if (node) {
    Object.assign(node, updates);
    updateModelValue();
  }
};

// 添加子节点
const addChild = (parentId) => {
  const parentNode = findNode(treeData.value, parentId);
  if (parentNode) {
    if (!parentNode.children) {
      parentNode.children = [];
    }
    parentNode.children.push(createNewNode());
    updateModelValue();
  }
};

// 添加兄弟节点
const addSibling = (nodeId) => {
  const parentNode = findParentNode(treeData.value, nodeId);

  if (parentNode) {
    // 有父节点，添加到父节点的children中
    const nodeIndex = parentNode.children.findIndex(
      (child) => child.id === nodeId,
    );
    parentNode.children.splice(nodeIndex + 1, 0, createNewNode());
  } else {
    // 没有父节点，说明是根节点，添加到根级别
    const nodeIndex = treeData.value.findIndex((node) => node.id === nodeId);
    treeData.value.splice(nodeIndex + 1, 0, createNewNode());
  }

  updateModelValue();
};

// 删除节点
const removeNode = (nodeId) => {
  const removeFromArray = (nodes) => {
    const index = nodes.findIndex((node) => node.id === nodeId);
    if (index !== -1) {
      nodes.splice(index, 1);
      return true;
    }

    for (let node of nodes) {
      if (node.children && removeFromArray(node.children)) {
        return true;
      }
    }
    return false;
  };

  removeFromArray(treeData.value);
  updateModelValue();
};

// 监听外部数据变化
watch(() => props.modelValue, initializeData, { immediate: true, deep: true });

// 更新父组件绑定的值
const updateModelValue = () => {
  emit('update:modelValue', treeData.value);
};

// 初始化
initializeData();
</script>

<style lang="scss" scoped>
.tree-editor {
  .empty-state {
    text-align: center;
    padding: 20px;
    border: 2px dashed #dcdfe6;
    border-radius: 4px;
    color: #909399;
  }

  .tree-container {
    // border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
  }
}
</style>
